﻿using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Text;
using CommDll;
using System.Xml.Linq;
using System.Xml;
using System.Drawing;
using System.ComponentModel;
using DevComponents.DotNetBar.Controls;
namespace InstitutionAssitant
{
    /// <summary>
    /// ClassName:frmQuery_MedicineCodeCheck
    /// Version:1.0
    /// Date:2019-06-23
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为实现药品对码(先确定本地药品信息)
    /// </remarks>
    public partial class frmQuery_MedicineCodeCheck : DevComponents.DotNetBar.OfficeForm
    {
        #region 01 自定义属性
        public Dictionary<string, string> m_dictInfo = new Dictionary<string, string>(); // 回传信息
        #endregion

        public frmQuery_MedicineCodeCheck()
        {
            InitializeComponent();
        }
  
        #region 003 自定义方法
        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strInfo = "";
            string strKind = "";
            strKind = this.Name + "0";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,SupplierCode-配企编号,SupplierName-配企名称,Code-药品编码,Code_His-药品编码HIS,Name-药品名称,Name_His-药品名称HIS,Spec-规格,Spec_His-规格HIS,Manufacturer-生产厂家,Manufacturer_His-生产厂家HIS"
            +",Form-剂型,Form_His-剂型HIS,RegistrationCode-批准文号,RegistrationCode_His-批准文号HIS,Unit-单位,Unit_His-单位HIS,UnitMinForm-剂型单位,Price-价格,Price_His-价格HIS,WarehouseRatio-转换率,WarehouseCode-药库编号,WarehouseName-药库名称";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,SupplierCode,SupplierName,Code,Code_His,Name,Name_His,Spec,Spec_His,Manufacturer,Manufacturer_His"
            + ",Form,Form_His,RegistrationCode,RegistrationCode_His,Unit,Unit_His,UnitMinForm,Price,Price_His,WarehouseRatio,WarehouseCode,WarehouseName";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "0,0,200,0,0,140,140,140,140,140,140,0,0,120,120,80,80,0,80,80,80,80,80";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);

            strKind = this.Name + "1";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,Code-药品编码,Name-药品名称,ApprovalNumber-批准文号,Form-剂型,PackageSpec-规格,Unit-单位,PackageRatio-包装比,Manufacturer-生产厂家,WarehouseCode-库房编码,WarehouseName-库房名称,Price-价格";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,Kind,Code,Name,ApprovalNumber,Price,PackageSpec,Unit,Manufacturer,PackageRatio,WarehouseCode,WarehouseName,Form";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            strInfo = "ID,Kind,Code,Name,ApprovalNumber,Price,PackageSpec,Unit,Manufacturer,PackageRatio,WarehouseCode,WarehouseName,Form";
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "0,0,100,200,140,80,140,60,120,60,80,80,80";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);
        }

        /// <summary>
        /// 查询配企药品信息
        /// </summary>
        private void _queryGoods0()
        {
            string strWhere = "";
            string strTemp = "", strTemp1 = "";
            try
            {
                // 01 取条件
                // 0101 条件1
                strTemp1 = txtWhere.Text.Trim();
                if (!strTemp1.Equals("") && (cbWhere01.Checked || cbWhere02.Checked || cbWhere03.Checked || cbWhere04.Checked))
                {
                    if (cbWhere01.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Code like '%{0}%'", strTemp1);
                    }
                    if (cbWhere02.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Name like '%{0}%'", strTemp1);
                    }
                    if (cbWhere03.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("RegistrationCode like '%{0}%'", strTemp1);
                    }
                    if (cbWhere04.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Manufacturer like '%{0}%'", strTemp1);
                    }
                    strWhere = string.Format(" and ({0})", strTemp);
                }
                // 0102 取状态
                if (cbState0.Checked || cbState1.Checked)
                {
                    strTemp = "";
                    if (cbState0.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("len(isnull(Code_His,'')) < 1", 0);
                    }
                    if (cbState1.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("len(isnull(Code_His,'')) > 0", 0);
                    }                    
                    strWhere += string.Format(" and ({0})", strTemp);
                }
                
                // 02 取数据
                string strSql = string.Format("SELECT {0} FROM V_DeliveryDetail where ID in (select Max(ID) as ID from T_DeliveryDetail  group by SupplierCode,Code) {{0}} order by ID", AppConfig.m_dictFieldSql[this.Name + "0"]); 
                strSql = string.Format(strSql, strWhere);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 03 显示数据
                    // 0301 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name + "0"]);
                    // 0302 显示数据
                    CommFun._showDataGridView0(dgv0, dt, AppConfig.m_dictFieldWidth[this.Name + "0"], AppConfig.m_dictFieldName[this.Name + "0"]);
                    // 0303 显示明细数据
                    dgv0_CellClick(dgv0, new DataGridViewCellEventArgs(dgv0.Columns["Name"].Index, 0));
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgv0.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
            // 02 清除匹配数据
            _clearGoodsInfo1();
        }

        /// <summary>
        /// 查询HIS药品信息
        /// </summary>
        private void _queryGoods1()
        {
            try
            {
                // 01 条件
                string strWhere = "", strTemp = "";
                string strTemp1 = txtWhere1.Text.Trim();
                if (!strTemp1.Equals("") && (cbWhere11.Checked || cbWhere12.Checked || cbWhere13.Checked || cbWhere14.Checked))
                {
                    if (cbWhere11.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Code like '%{0}%' ", strTemp1);
                    }
                    if (cbWhere12.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Name like '%{0}%' ", strTemp1);
                    }
                    if (cbWhere13.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("ApprovalNumber like '%{0}%' ", strTemp1);
                    }
                    if (cbWhere14.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Manufacturer like '%{0}%' ", strTemp1);
                    }                
                    strWhere = string.Format(" where  ({0})", strTemp);
                }
                //else
                //{
                //    CommFun._messageBoxShow("查询条件不能为空!");
                //    return;
                //}
               
                // 03 取数据
                string strSql = string.Format("SELECT {0} FROM TH_Goods {{0}} order by ID", AppConfig.m_dictFieldSql[this.Name + "1"]);
                strSql = string.Format(strSql,strWhere);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 04 显示数据
                    // 0401 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name + "1"]);
                    // 0402 显示数据
                    CommFun._showDataGridView0(dgv1, dt, AppConfig.m_dictFieldWidth[this.Name + "1"], AppConfig.m_dictFieldName[this.Name + "1"]);
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgv1.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 清除匹配信息
        /// </summary>
        private void _clearGoodsInfo1()
        {
            txtWhere1.Text = "";
            if (dgv1.Rows.Count > 0)
            {
                ((DataTable)dgv1.DataSource).Rows.Clear();
            }
        }

        /// <summary>
        /// 药品对码
        /// </summary>
        private void _checkMedicineCode()
        {
            try
            {
                frmGoodsCodeCheck frm = new frmGoodsCodeCheck();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    _updateMedicine();
                }                
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 更新对码数据
        /// </summary>
        private void _updateMedicine()
        {
            try
            {
                // 更新所有数据
                DataRow dr0 = DbHelper.DBAccess[0]._openSql_Row(string.Format("select * from V_DeliveryDetail where ID = {0}", ModelGoodsCodeCheck.strID0));
                string strTemp = "Code_His,Name_His,Spec_His,Manufacturer_His,RegistrationCode_His,Form_His,Unit_His,WarehouseRatio,Price_His,Price_Warehouse,WarehouseCode,WarehouseName";
                DataTable DataTable0 = (DataTable)dgv0.DataSource;
                foreach (string str in strTemp.Split(','))
                {
                    if (DataTable0.Columns.Contains(str))
                    {
                        DataTable0.Columns[str].ReadOnly = false;
                        if (dr0[str].ToString().Length < 1)
                        {
                            dgv0.Rows[dgv0.CurrentRow.Index].Cells[str].Value = DBNull.Value;
                        }
                        else { 
                            dgv0.Rows[dgv0.CurrentRow.Index].Cells[str].Value = dr0[str].ToString();
                        }
                    }
                }                                
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }
        #endregion

        #region 004 窗体相关事件方法
        private void frmQuery_MedicineCodeCheck_Load(object sender, EventArgs e)
        {
            timerInit.Enabled = true;
            dgv0.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            dgv1.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
        }

        private void timerInit_Tick(object sender, EventArgs e)
        {
            timerInit.Enabled = false;
            // 初始化DataGridView
            _initDgvTitle();            
        }

        private void btnQuery0_Click(object sender, EventArgs e)
        {
            _queryGoods0();
        }
        
        private void btnQuery1_Click(object sender, EventArgs e)
        {
            _queryGoods1();
        }

        private void txtWhere0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery0_Click(null, null);
            }
        }

        private void txtWhere1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery1_Click(null, null);
            }
        }        
        #endregion

        #region  DataGridView 事件方法        

        private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            CommFun._dgvColumnHeaderSort(sender, e);
        }

        private void dgv0_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 取数据
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            DataGridView dgv = (DataGridView)sender;
            // 取配企数据
            ModelGoodsCodeCheck.strSupplierCode = dgv.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToString();
            ModelGoodsCodeCheck.strID0 = dgv.Rows[e.RowIndex].Cells["ID"].Value.ToString();
            ModelGoodsCodeCheck.strCode0 = dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString();            
            ModelGoodsCodeCheck.strName0 = dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString();            
            ModelGoodsCodeCheck.strRegistrationCode0 = dgv.Rows[e.RowIndex].Cells["RegistrationCode"].Value.ToString();
            ModelGoodsCodeCheck.strManufacturer0 = dgv.Rows[e.RowIndex].Cells["Manufacturer"].Value.ToString();
            ModelGoodsCodeCheck.strSpec0 = dgv.Rows[e.RowIndex].Cells["Spec"].Value.ToString();            
            ModelGoodsCodeCheck.strUnit0 = dgv.Rows[e.RowIndex].Cells["Unit"].Value.ToString();
            ModelGoodsCodeCheck.strUnitMinForm0 = dgv.Rows[e.RowIndex].Cells["UnitMinForm"].Value.ToString();
            ModelGoodsCodeCheck.strForm0 = dgv.Rows[e.RowIndex].Cells["Form"].Value.ToString();
            ModelGoodsCodeCheck.dWarehouseRatio0 = FunctionComm._strToFloat(dgv.Rows[e.RowIndex].Cells["WarehouseRatio"].Value.ToString(), 1);
            ModelGoodsCodeCheck.strWarehouseCode0 = dgv.Rows[e.RowIndex].Cells["WarehouseCode"].Value.ToString();
            ModelGoodsCodeCheck.strWarehouseName0 = dgv.Rows[e.RowIndex].Cells["WarehouseName"].Value.ToString();

            // 按指定信息查询数据
            string strTemp = dgv.Columns[e.ColumnIndex].Name;            
            cbWhere11.Checked = false;
            cbWhere12.Checked = false;
            cbWhere13.Checked = false;
            cbWhere14.Checked = false;
            if ("Code,Name,RegistrationCode,Manufacturer".Contains(strTemp))
            {
                switch (strTemp)
                {
                    case "Code":
                        cbWhere11.Checked = true;
                        break;
                    case "Name":
                        cbWhere12.Checked = true;
                        break;
                    case "RegistrationCode":
                        cbWhere13.Checked = true;
                        break;
                    case "Manufacturer":
                        cbWhere14.Checked = true;
                        break;
                }
                txtWhere1.Text = dgv0.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                btnQuery1_Click(null, null);
            }
            else
            {
                _clearGoodsInfo1();
            }
        }

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 对码操作
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            DataGridView dgv = (DataGridView)sender;
            switch (dgv.Name)
            {
                case "dgv0":
                    // 对码操作:暂不对码                    
                    if (CommFun._messageBoxShow("确认设置成【暂不对码】？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                    {
                        try
                        {
                            ModelGoodsCodeCheck.strCode1 = "";
                            ModelGoodsCodeCheck._saveInfo();
                            // 更新数据
                            _updateMedicine();
                        }
                        catch (Exception ex)
                        {
                            CommFun._messageBoxShow(ex.Message);
                            return;
                        }
                    }                    
                    break;
                case "dgv1":
                    if (dgv0.CurrentRow == null)
                    {
                        CommFun._messageBoxShow("请先确定配企药品数据！");
                        return;
                    }
                    // 数据初始化
                    ModelGoodsCodeCheck.strCode1 = dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString();
                    ModelGoodsCodeCheck.strUnit1 = dgv.Rows[e.RowIndex].Cells["Unit"].Value.ToString();
                    ModelGoodsCodeCheck.strName1 = dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString();
                    ModelGoodsCodeCheck.strForm1 = dgv.Rows[e.RowIndex].Cells["Form"].Value.ToString();
                    ModelGoodsCodeCheck.strRegistrationCode1 = dgv.Rows[e.RowIndex].Cells["ApprovalNumber"].Value.ToString();
                    ModelGoodsCodeCheck.strSpec1 = dgv.Rows[e.RowIndex].Cells["PackageSpec"].Value.ToString();
                    ModelGoodsCodeCheck.strManufacturer1 = dgv.Rows[e.RowIndex].Cells["Manufacturer"].Value.ToString();
                    ModelGoodsCodeCheck.strWarehouseCode1 = dgv.Rows[e.RowIndex].Cells["WarehouseCode"].Value.ToString();
                    ModelGoodsCodeCheck.strWarehouseName1 = dgv.Rows[e.RowIndex].Cells["WarehouseName"].Value.ToString();
                    ModelGoodsCodeCheck.dPrice1 = FunctionComm._strToFloat(dgv.Rows[e.RowIndex].Cells["Price"].Value.ToString()); 
                    // 对码
                    _checkMedicineCode();
                    break;
            }
        }        

        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender, e);
        }

        private void dataGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 设置标题信息    
            if (e.Button == MouseButtons.Right)
            {
                DataGridView dgv = (DataGridView)sender;
                frmDataShowSetup frm = new frmDataShowSetup();
                switch (dgv.Name)
                {
                    case "dgv0":
                        frm.m_strInfoKind = this.Name + "0";
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            if (frm.m_bIsSaveWidth)
                            {
                                // 保存宽度
                                AppConfig._saveDgvWidth(dgv0, frm.m_strInfoKind);
                                CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                if (dgv0.Rows.Count > 0)
                                {
                                    btnQuery0_Click(null, null);
                                }
                            }
                        }
                        break;
                    case "dgv1":
                        frm.m_strInfoKind = this.Name + "1";
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            if (frm.m_bIsSaveWidth)
                            {
                                // 保存宽度
                                AppConfig._saveDgvWidth(dgv1, frm.m_strInfoKind);
                                CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                if (dgv0.Rows.Count > 0)
                                {
                                    btnQuery1_Click(null, null);
                                }
                            }
                        }
                        break;
                }
            }
        }
        #endregion
    }
}


